<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\cms\controller\project_meeting_invitation;

use plugin\saiadmin\basic\BaseController;
use app\cms\logic\project_meeting_invitation\ProjectMeetingInvitationSpeakerLogic;
use app\cms\logic\ProjectMeetingLogic;
use app\cms\logic\SpeakerLogic;
use app\cms\model\project_meeting_invitation\ProjectMeetingInvitationSpeaker;
use app\cms\model\ProjectMeeting;
use app\cms\validate\project_meeting_invitation\ProjectMeetingInvitationSpeakerValidate;
use support\Log;
use support\Request;
use support\Response;


/**
 * 邀请阶段控制器
 */
class ProjectMeetingInvitationSpeakerController extends BaseController
{
    /**
     * 构造函数
     */
    public function __construct()
    {

        $this->logic = new ProjectMeetingInvitationSpeakerLogic();
        $this->validate = new ProjectMeetingInvitationSpeakerValidate;
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        // $where = $request->more([
        //     ['speaker_name', ''],
        //     ['speaker_email', ''],
        //     ['meeting_type', ''],
        //     ['project_id', ''],
        //     ['project_meeting_id', ''],
        // ]);
        $where = $request->more([
            ['speaker_name', ''],
            ['project_id', ''],
            ['project_meeting_id', ''],
        ]);
        // $title = 
        // $query = $this->logic->search($where);
        $query = $this->logic->where('project_id', $where['project_id'])
            ->where('project_meeting_id', $where['project_meeting_id']);
        $query->whereRaw('speaker_name like ? or speaker_email like ?', ['%' . trim($where['speaker_name']) . '%', '%' . trim($where['speaker_name']) . '%']);
        // ->where('speaker_name', 'like', '%' . trim($where['speaker_name']) . '%');

        $query->with([
            'speaker' => function ($query) {
                $query->field('id,name,name_en,title');
            },
            'projectMeeting' => function ($query) {
                $query->field('id,status,is_display');
            },
        ]);

        $data = $this->logic->getList($query);
        return $this->success($data);
    }

    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $data = $request->post();

        if ($this->validate) {
            if (!$this->validate->scene('save')->check($data)) {
                return $this->fail($this->validate->getError());
            }
        }
        $projectMeetingInvitationSpeaker = ProjectMeetingInvitationSpeaker::where(['project_meeting_id' => $data['project_meeting_id'], 'speaker_id' => $data['speaker_id'], 'invitation_status' => 1])->find();
        if (!empty($projectMeetingInvitationSpeaker)) {
            return $this->fail('专家已经参会');
        }
        Log::info('保存数据：' . json_encode($data));
        $result = $this->logic->save($data);
        Log::info('返回结果：' . json_encode($result));
        if ($result) {
            $res = $this->logic->order('id', 'desc')->find();
            Log::info('成功结果：' . json_encode($res));
            $res = $this->afterSave($res);
            return $this->success('操作成功');
        } else {
            return $this->fail('操作失败');
        }
    }

    public function afterSave($data)
    {
        $projectMeetingLogic = new ProjectMeetingLogic();
        $projectMeetingLogic->where('id', $data['project_meeting_id'])->setInc('total_invitation', 1);
    }

    /**
     * 读取数据
     * @param Request $request
     * @param $id
     * @return Response
     */
    public function read(Request $request, $id): Response
    {
        $id = $request->input('id', $id);
        $model = $this->logic->with(
            [
                'projectMeeting' => function ($query) {
                    $query->field('id,meeting_name,status,is_display');
                }
            ]
        )->find($id);
        if ($model) {
            $data = is_array($model) ? $model : $model->toArray();
            return $this->success($data);
        } else {
            return $this->fail('未查找到信息');
        }
    }

    /**
     * 删除数据
     * @param Request $request
     * @return Response
     */
    public function destroy(Request $request): Response
    {
        $ids = $request->input('ids', '');
        $projectMeetingId = $this->logic->whereIn('id',  implode(',', $ids))->value('project_meeting_id');
        if (!empty($ids)) {
            $res = $this->logic->destroy($ids);
            if ($res) {
                $count = count($ids);
                $this->afterDelete($projectMeetingId, $count);
            }
            return $this->success('操作成功');
        } else {
            return $this->fail('参数错误，请检查');
        }
    }

    public function afterDelete($id, $count)
    {
        ProjectMeeting::where('id', $id)->dec('total_invitation', $count)->update();
    }

    /**
     * 邀请阶段-添加邀请-外讲下拉菜单
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-08-20
     * @return void
     */
    public function getSpeaker()
    {
        $logic = new SpeakerLogic();
        $data = $logic->where('status', 1)->field('id,name,email,title')->order('id desc')->select();
        return $this->success($data);
    }

    /**
     * 修改邀请状态
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-08-20
     * @return void
     */
    public function auditInvitationStatus(Request $request)
    {
        $id = $request->input('id', '');
        $invitation_status = $request->input('invitation_status', '');
        $invitation_remarks = $request->input('invitation_remarks', '');
        $project = $this->logic->where('id', $id)->update([
            'invitation_status' => $invitation_status,
            'invitation_remarks' => $invitation_remarks ? $invitation_remarks : null,
            'audit_time' => $invitation_status == -1 || $invitation_status == -2 ? date('Y-m-d H:i:s', time()) : null,
        ]);
        if ($project) {
            $this->afterAudit($id, $invitation_status);
            return $this->success('操作成功');
        } else {
            return $this->fail('操作失败');
        }
    }

    /**
     * 修改邀请状态之后修改会议的受邀数量
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2025-01-08
     * @param [type] $id
     * @param [type] $status
     * @return void
     */
    public function afterAudit($id, $status)
    {
        $projectMeetingInvitationSpeaker = $this->logic->where('id', $id)->find();
        // 根据受邀讲者表id获取这个会议的所有邀请讲者，判断受邀数据，修改会议表
        $invitationSpeakerCount = $this->logic->where('project_meeting_id', $projectMeetingInvitationSpeaker['project_meeting_id'])->where('invitation_status', 1)->count();

        $projectMeetingLogic = new ProjectMeetingLogic();

        $projectMeetingLogic->where('id', $projectMeetingInvitationSpeaker['project_meeting_id'])->update(['confirm_invitation' => $invitationSpeakerCount]);
    }

    /**
     * 查看原因
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-08-20
     * @param Request $request
     * @return void
     */
    public function checkInvitationRemarks(Request $request)
    {
        $id = $request->input('id', '');
        $remarks = $this->logic->where('id', $id)->value('invitation_remarks');
        if ($remarks) {
            return $this->success(['remarks' => $remarks], '操作成功');
        } else {
            return $this->fail('未找到原因');
        }
    }

    /**
     * 沟通阶段列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-08-20
     * @param Request $request
     * @return void
     */
    public function getCommunicationPhase(Request $request)
    {

        $where = $request->more([
            ['project_meeting_id', ''],
            ['meeting_type', ''],
            ['speaker_name', ''],
            ['speaker_email', ''],
            ['id', ''], // 邀请表主键id
            // ['invitation_status', 1],
            // ['is_fill_info' => ['!=', 0]]
        ]);

        $reload = [];
        if ($where['meeting_type'] == 1) {
            $reload = [
                // 线上会议信息+测试需求给到讲者
                'meetingOnline' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,conference_number,password,conference_url,conference_is_display,is_test,test_time,test_is_display,is_display');
                },
                // 可编辑日程翻译给讲者
                'meetingSchedule' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,schedule_url');
                },
                // 会后感谢信
                'meetingAfter' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display');
                },
            ];
        } elseif ($where['meeting_type'] == 2) {
            $reload = [
                // 签证计划
                'visaProgram' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display');
                },
                // 签证包发送
                'visaPackage' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,file_name,visa_url');
                },
                // 邀请函
                'invitationLetter' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,letter_url');
                },
                // 邀请函邮寄发单号
                'invitationLetterNumber' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,letter_number');
                },
                // @todo  更新外讲表  eb_speaker_resume  的常旅客号
                // 索要常旅客号
                'frequentFlyer' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,frequent_flyer_number');
                },
                // 发讲者喜好问卷
                'meetingQuestions' =>  function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,file_name,questionnaire_url');
                },
                // 行程终版+国际机票+酒店信息给讲者
                'finalTravel' =>  function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,final_travel,ticket,hotel');
                },
                // 索要中国签证扫描页
                'chinaVsiaScan'  => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,scan_url');
                },
                // 接机安排和温馨提示等
                'pickUpAndTips'  => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display');
                },
                // 活动感谢信+询问报销+出入境章扫描件
                'scan'  => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,thank_you,reimbursement,scan');
                },
                // 索要报销单据扫描件
                'reimbursement'  => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,reimbursement_url');
                },
                // 发结算单
                'statement' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,final_statement_url');
                },
            ];
        }

        $query = $this->logic->search($where);

        $query->whereRaw('invitation_status = 1 and is_fill_info >=0 or (invitation_status = -1 and is_fill_info > 0)');
        // $query->where('invitation_status', 1);
        // $query->whereOr(['invitation_status' => -1, 'is_fill_info' => ['>', 0]]);
        // $query->whereIn('invitation_status', '1,-1');
        // $query->where(['invitation_status' => -1, 'is_fill_info' => ['>', 0]]);
        $query->with(array_merge([
            // 关联资料上传表
            'uploadData' => function ($query) {
                $query->field(
                    ' id,
                                invitation_speaker_id,
                                meeting_time_bj,
                                meeting_time_en,
                                meeting_start_time,
                                meeting_end_time,
                                service_charge,
                                payer,
                                meeting_info_is_display,
                                meeting_materiel,
                                meeting_screen_recording,
                                meeting_photo,
                                meeting_materiel_is_display,
                                meeting_ppt,
                                meeting_ppt_is_display,
                                currency_type'

                );
            },
            // cuc账户录入
            'cuc' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display');
            },
            // 劳务费支付
            'charge' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display');
            },
            // @todo  如果外讲库的讲者简历、护照、付款信息有的话用那俩表的eb_speaker_passport、eb_speaker_resume
            // 索要讲者简历+照片
            'speakerResume' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,speaker_resume,speaker_resume_translate,speaker_avatar');
            },
            // @todo  更新 eb_speaker_reme表付款信息
            // 索要讲者付款信息+护照 
            'speakerPassport' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,remittance,surname,name,birth,passport_number,nationality,sex,place_of_birth,passport_issuing_place,validity,upload_passport');
            },
            // 签订协议
            'signAgreement' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,sign_agreement_url');
            },
            // PPT要求及返回截止日期
            'pptReturnDeadline' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,ppt_return_deadline');
            },
            // PPT跟进
            'pptFollowUp' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,ppt_follow_up');
            },
            // 翻译PPT给到讲者
            'pptTranslate' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,ppt_translate');
            },
            // 翻译讨论问题给讲者
            'translateToLecturer' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,ppt_translate_problem');
            },
            'speaker' => function ($query) {
                $query->with([
                    'resume',
                    'passport'
                ])
                    ->field('id,institution,institution_cn,institution_en,photo,title,name')->where('status', 1);
            },
            'project' => function ($query) {
                $query->field('id,project_name');
            },
            'projectMeeting' => function ($query) {
                $query->field('id,meeting_name,status,is_display');
            }

        ], $reload));

        $data = $this->logic->getList($query);
        return $this->success($data);
    }

    /**
     * 获取资料详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-11
     * @param Request $request
     * @return void
     */
    public function getCommunicationPhaseDetail(Request $request)
    {
        $where = $request->more([
            ['id', ''],
            ['meeting_type', ''],
        ]);
        if ($where['meeting_type'] == 1) {
            $reload = [
                // 线上会议信息+测试需求给到讲者
                'meetingOnline' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,conference_number,password,conference_url,conference_is_display,is_test,test_time,test_is_display,is_display');
                },
                // 可编辑日程翻译给讲者
                'meetingSchedule' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,schedule_url');
                },
                // 会后感谢信
                'meetingAfter' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display');
                },
            ];
        } elseif ($where['meeting_type'] == 2) {
            $reload = [
                // 签证计划
                'visaProgram' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display');
                },
                // 签证包发送
                'visaPackage' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,file_name,visa_url');
                },
                // 邀请函
                'invitationLetter' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,letter_url');
                },
                // 邀请函邮寄发单号
                'invitationLetterNumber' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,letter_number');
                },
                // @todo  更新外讲表  eb_speaker_resume  的常旅客号
                // 索要常旅客号
                'frequentFlyer' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,frequent_flyer_number');
                },
                // 发讲者喜好问卷
                'meetingQuestions' =>  function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,file_name,questionnaire_url');
                },
                // 行程终版+国际机票+酒店信息给讲者
                'finalTravel' =>  function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,final_travel,ticket,hotel');
                },
                // 索要中国签证扫描页
                'chinaVsiaScan'  => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,scan_url');
                },
                // 接机安排和温馨提示等
                'pickUpAndTips'  => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display');
                },
                // 活动感谢信+询问报销+出入境章扫描件
                'scan'  => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,thank_you,reimbursement,scan');
                },
                // 索要报销单据扫描件
                'reimbursement'  => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,reimbursement_url');
                },
                // 发结算单
                'statement' => function ($query) {
                    $query->field('id,invitation_speaker_id,status,remarks,is_display,final_statement_url');
                },
            ];
        }

        // $query = $this->logic->search($where);
        $withModel = array_merge([
            // 关联资料上传表
            'uploadData' => function ($query) {
                $query->field(' id,
                                invitation_speaker_id,
                                meeting_time_bj,
                                meeting_time_en,
                                meeting_start_time,
                                meeting_end_time,
                                service_charge,
                                payer,
                                meeting_info_is_display,
                                meeting_materiel,
                                meeting_screen_recording,
                                meeting_photo,
                                meeting_materiel_is_display,
                                meeting_ppt,
                                meeting_ppt_is_display,
                                currency_type');
            },
            // cuc账户录入
            'cuc' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display');
            },
            // 劳务费支付
            'charge' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display');
            },
            // @todo  如果外讲库的讲者简历、护照、付款信息有的话用那俩表的eb_speaker_passport、eb_speaker_resume
            // 索要讲者简历+照片
            'speakerResume' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,speaker_resume,speaker_resume_translate,speaker_avatar');
            },
            // @todo  更新 eb_speaker_resume表付款信息
            // 索要讲者付款信息+护照 
            'speakerPassport' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,remittance,surname,name,birth,passport_number,nationality,sex,place_of_birth,passport_issuing_place,validity,upload_passport');
            },
            // 签订协议
            'signAgreement' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,sign_agreement_url');
            },
            // PPT要求及返回截止日期
            'pptReturnDeadline' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,ppt_return_deadline');
            },
            // PPT跟进
            'pptFollowUp' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,ppt_follow_up');
            },
            // 翻译PPT给到讲者
            'pptTranslate' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,ppt_translate');
            },
            // 翻译讨论问题给讲者
            'translateToLecturer' => function ($query) {
                $query->field('id,invitation_speaker_id,status,remarks,is_display,ppt_translate_problem');
            },
            'speaker' => function ($query) {
                $query->with([
                    'resume',
                    'passport'
                ])
                    ->field('id,institution,institution_cn,institution_en,title,name,name_en')->where('status', 1);
            },
            'project' => function ($query) {
                $query->field('id,project_name');
            },
            'projectMeeting' => function ($query) {
                $query->field('id,meeting_name,status,is_display');
            }

        ], $reload);

        $data = ProjectMeetingInvitationSpeaker::where('id', $where['id'])->with($withModel)->find();
        return $this->success($data);
    }
}
